package com.astrofizzbizz.stoneedgegui.monitor;

import java.awt.Color;
import java.util.Date;

import javax.swing.JLabel;

import com.astrofizzbizz.stoneedgegui.utilities.StoneEdgeIIIException;
import com.astrofizzbizz.stoneedgegui.utilities.TreffersLock;



public class DomeMonitor implements Runnable
{
	private boolean backgroundMonitoringOn = false;
	private boolean lineEcho;
	private JLabel trackingOffLabel = new JLabel("Tracking status unknown");
	private JLabel domeLocationLabel = new JLabel("Dome Location unknown");
	private JLabel slitClosedLabel = new JLabel("Slit status unknown");
	private JLabel cantOpenReasonLabel = new JLabel("Can't open status unknown");
	private JLabel lockNameLabel = new JLabel(" ");
	private JLabel lockPhoneLabel = new JLabel(" ");
	private TelescopeMonitorPanel telescopeMonitorPanel;
	private boolean trackingOff = true;
	private boolean slitClosed = true;
	private boolean domeCanOpen = false;
	private double domeLocation = -1;
	private TreffersLock treffersLock;
	private boolean keepTrackingOn = false;
	private int trackingCount = 0;
	private boolean ourLockOn = false;
	
	DomeMonitor(boolean  lineEcho, TelescopeMonitorPanel telescopeMonitorPanel)
	{
		this.lineEcho = lineEcho;
		this.telescopeMonitorPanel = telescopeMonitorPanel;
	}
	public boolean isTrackingOff() {return trackingOff;}
	public boolean isSlitClosed() {return slitClosed;}
	public boolean isDomeCanOpen() {return domeCanOpen;}
	public double getDomeLocation() {return domeLocation;}
	public TreffersLock getTreffersLock() {return treffersLock;}
	public void updateMonitor()
	{
		String info = null;
		try 
		{
			telescopeMonitorPanel.getStoneEdgeIIIGui().getTelescopeInfo().update();
			info = "Telescope Ra, Dec, and limits updated";
			if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(info);
		} catch (StoneEdgeIIIException e2) 
		{
			info = "ERROR: Telescope Ra, Dec, and limits not found!";
			if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(info);
		}
		try 
		{
			String statusTable = TelescopeStatus.statusTable(
					telescopeMonitorPanel.getStoneEdgeIIIGui().getStatusTableLength(), 
					telescopeMonitorPanel.getStoneEdgeIIIGui().getStoneEdgeIIITunnel());
			telescopeMonitorPanel.getTelescopeStatusTableTextArea().setText(statusTable);
		} 
		catch (StoneEdgeIIIException e1) 
		{
			String statusTable = "ERROR: No data";
			telescopeMonitorPanel.getTelescopeStatusTableTextArea().setText(statusTable);
		}
		try 
		{
			trackingOff = TelescopeStatus.trackingOff(telescopeMonitorPanel.getStoneEdgeIIIGui().getStoneEdgeIIITunnel());
			if(trackingOff)
			{
				info = "Tracking Off";
				trackingOffLabel.setText(info);
				trackingOffLabel.setForeground(Color.red);
				if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(info);
			}
			else
			{
				info = "Tracking On";
				trackingOffLabel.setText(info);
				trackingOffLabel.setForeground(Color.green);
				if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(info);
			}
		} catch (StoneEdgeIIIException e) 
		{
			info = "Tracking status UNKNOWN";
			trackingOffLabel.setText(info);
			trackingOffLabel.setForeground(Color.red);
			if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(info);
		}
		try 
		{
			slitClosed = TelescopeStatus.slitClosed(telescopeMonitorPanel.getStoneEdgeIIIGui().getStoneEdgeIIITunnel());
			if(slitClosed)
			{
				info = "Slit Closed";
				slitClosedLabel.setText(info);
				slitClosedLabel.setForeground(Color.red);
				if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(info);
			}
			else
			{
				info = "Slit Open";
				slitClosedLabel.setText(info);
				slitClosedLabel.setForeground(Color.green);
				if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(info);
			}
		}
		catch (StoneEdgeIIIException e) 
		{
			info = "Slit Status UNKNOWN";
			slitClosedLabel.setText(info);
			slitClosedLabel.setForeground(Color.red);
			if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(info);
		}
		try 
		{
			String cantOpenReason = TelescopeStatus.cantOpenReason(telescopeMonitorPanel.getStoneEdgeIIIGui().getStoneEdgeIIITunnel());
			if (cantOpenReason.equals("Dome Open"))
			{
				info = "Dome Open";
				domeCanOpen = false;
				if(telescopeMonitorPanel.isVisible())
				{
					telescopeMonitorPanel.getDomeMonitorPanel().getDomeOpenCloseButton()[0].setVisible(false);
					telescopeMonitorPanel.getDomeMonitorPanel().getDomeOpenCloseButton()[1].setVisible(true);
				}
				cantOpenReasonLabel.setText(info);
				cantOpenReasonLabel.setForeground(Color.green);
				if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(info);
			}
			else
			{
				if (cantOpenReason.equals("Dome Can Open"))
				{
					info = "Dome Can Open";
					domeCanOpen = true;
					if(telescopeMonitorPanel.isVisible())
					{
						telescopeMonitorPanel.getDomeMonitorPanel().getDomeOpenCloseButton()[0].setVisible(true);
						telescopeMonitorPanel.getDomeMonitorPanel().getDomeOpenCloseButton()[1].setVisible(false);
					}
					cantOpenReasonLabel.setText(info);
					cantOpenReasonLabel.setForeground(Color.green);
					if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(info);
				}
				else
				{
					info = "Dome Cannot open. Reason: " + cantOpenReason;
					domeCanOpen = false;
					if(telescopeMonitorPanel.isVisible())
					{
						telescopeMonitorPanel.getDomeMonitorPanel().getDomeOpenCloseButton()[0].setVisible(false);
						telescopeMonitorPanel.getDomeMonitorPanel().getDomeOpenCloseButton()[1].setVisible(false);
					}
					cantOpenReasonLabel.setText(info);
					cantOpenReasonLabel.setForeground(Color.red);
					if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(info);
				}
			}
		}
		catch (StoneEdgeIIIException e) 
		{
			info = "Dome open reason: UNKNOWN";
			cantOpenReasonLabel.setText(info);
			cantOpenReasonLabel.setForeground(Color.red);
			if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(info);
		}
		try 
		{
			Double domeLocationDouble = new Double(TelescopeStatus.domeLocation(telescopeMonitorPanel.getStoneEdgeIIIGui().getStoneEdgeIIITunnel()));
			info = "Dome Location = " + domeLocationDouble.toString();
			domeLocation = domeLocationDouble.doubleValue();
			domeLocationLabel.setText(info);
			if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(info);
		}
		catch (StoneEdgeIIIException e) 
		{
			info = "Dome Location UNKNOWN";
			domeLocationLabel.setText(info);
			domeLocationLabel.setForeground(Color.red);
			if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(info);
		}
		
		try 
		{
			treffersLock = new TreffersLock(telescopeMonitorPanel.getStoneEdgeIIIGui().getStoneEdgeIIITunnel());
		    if (treffersLock.isLock())
		    {
				if ( telescopeMonitorPanel.getStoneEdgeIIIGui().getUserKey().equals(treffersLock.getSessionID()))
				{
					setOurLockOn(true);
				}
				else
				{
					setOurLockOn(false);
				}
		    	info = "Telescope locked by: " + treffersLock.getEmail();
		    	lockNameLabel.setText(info);
				if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(info);
		    	info = "Phone: " + treffersLock.getPhone();
		    	lockPhoneLabel.setText(info);
				if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(info);
				if ( telescopeMonitorPanel.getStoneEdgeIIIGui().getUserKey().equals(treffersLock.getSessionID()))
				{
			    	lockNameLabel.setForeground(Color.green);
			    	lockPhoneLabel.setForeground(Color.green);
				}
				else
				{
			    	lockNameLabel.setForeground(Color.red);
			    	lockPhoneLabel.setForeground(Color.red);
				}
		    }
		    else
		    {
		    	info = "Telescope unlocked";
		    	lockNameLabel.setText(info);
				if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(info);
		    	lockPhoneLabel.setText(" ");
		    	lockNameLabel.setForeground(Color.blue);
		    	lockPhoneLabel.setForeground(Color.blue);
		    	setOurLockOn(false);
		    }					

		}
		catch (StoneEdgeIIIException e) 
		{
	    	info = "Telescope lock UNKNOWN";
	    	lockNameLabel.setText(info);
			if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(info);
	    	lockPhoneLabel.setText(" ");
	    	lockNameLabel.setForeground(Color.red);
		}

		info = "Dome Status updated";
		telescopeMonitorPanel.getStatusBar().setText(info);
		if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(info);
		telescopeMonitorPanel.getStoneEdgeIIIGui().getUpdateDate().setTime(new Date().getTime());
		try 
		{
			if (telescopeMonitorPanel.getStoneEdgeIIIGui().getAstroCatalog() != null)
			{
				telescopeMonitorPanel.getStoneEdgeIIIGui().getAstroCatalog().upDate();
				if (lineEcho) telescopeMonitorPanel.getStoneEdgeIIIGui().getStatusBar().setText("Catalog updated");
				telescopeMonitorPanel.getStoneEdgeIIIGui().getTargetingPanel().update();
				if (lineEcho) telescopeMonitorPanel.getStoneEdgeIIIGui().getStatusBar().setText("Target updated");
			}
		} 
		catch (StoneEdgeIIIException e) 
		{
		}
	}
	public void keepSlitAndTrackingOn() 
	{
		if (!slitClosed && keepTrackingOn)
		{
			if (isOurLockOn())
			{
				try {
					telescopeMonitorPanel.getStatusBar().setText("KEEPING TRACKING ON");

					String[] response = null;
					String command = "tx slit keepopen";
					response = telescopeMonitorPanel.getStoneEdgeIIIGui().getStoneEdgeIIITunnel().executeCommand(command, 1024);
					if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(response[0]);
					command = "tx track local";
					response = telescopeMonitorPanel.getStoneEdgeIIIGui().getStoneEdgeIIITunnel().executeCommand(command, 1024);
					if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(response[0]);
					command = "tx dome center";
					response = telescopeMonitorPanel.getStoneEdgeIIIGui().getStoneEdgeIIITunnel().executeCommand(command, 1024);
					if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(response[0]);

					String info = "Tracking Updated";
					telescopeMonitorPanel.getStatusBar().setText(info);
					if (lineEcho) telescopeMonitorPanel.getStatusBar().setText(info);
				} 
				catch (StoneEdgeIIIException e) 
				{
					e.messageDialog(telescopeMonitorPanel.getStoneEdgeIIIGui());
				}
			}
		}
	}
	public void setOurLockOn(boolean ourLockOn) {this.ourLockOn = ourLockOn;}

	public boolean isKeepTrackingOn() {return keepTrackingOn;}
	public boolean isOurLockOn() {return ourLockOn;}
	public void setKeepTrackingOn(boolean keepTrackingOn) 
	{
		if (keepTrackingOn && !this.keepTrackingOn) 
		{
			this.keepTrackingOn = keepTrackingOn;
			keepSlitAndTrackingOn();
		}
		else
		{
			this.keepTrackingOn = keepTrackingOn;
		}
	}
	public JLabel getTrackingOffLabel() {return trackingOffLabel;}
	public JLabel getDomeLocationLabel() {return domeLocationLabel;}
	public JLabel getSlitClosedLabel() {return slitClosedLabel;}
	public JLabel getCantOpenReasonLabel() {return cantOpenReasonLabel;}
	public JLabel getLockNameLabel() {return lockNameLabel;}
	public JLabel getLockPhoneLabel() {return lockPhoneLabel;}

	@Override
	public void run() 
	{
		backgroundMonitoringOn = true;
		trackingCount = 0;
		while (backgroundMonitoringOn)
		{
			System.out.println("Running Update");
			updateMonitor();
			if (keepTrackingOn)
			{
				trackingCount = trackingCount + 1;
				if (trackingCount == telescopeMonitorPanel.getStoneEdgeIIIGui().getDomeTrackingIntervalHeartBeatCount())
				{
					keepSlitAndTrackingOn();
					trackingCount = 0;
				}
			}
			try {Thread.sleep(telescopeMonitorPanel.getStoneEdgeIIIGui().getDomeSleepTimerSeconds() * 1000);} catch (InterruptedException e) {;}

		}
	}
	
}
